package purchase

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strings"
)

/**
结算单
*/

func Settlement(r *gin.RouterGroup) {
	settlement := r.Group("/settlement")
	{
		settlement.POST(sql.RequestAdd, settlementBillAdd)
		settlement.POST(sql.RequestUpdate, settlementBillUpdate)
		settlement.GET(sql.RequestList, settlementBillList)
		settlement.GET(sql.RequestDelete, settlementBillDelete)
		settlement.GET(sql.RequestData, settlementBillData)
	}
}

func settlementBillAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.SettlementBill{}, nil)
}

func settlementBillUpdate(c *gin.Context) {
	sql.HttpUpdates(c, &model.SettlementBill{}, nil)
}

func settlementBillList(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var settlementBill []model.SettlementBill
		id := c.Query("purchaseProductId")
		tx := db.Begin()
		if err := tx.Where("purchase_product_id = ?", id).Find(&settlementBill).Error; err != nil {
			tx.Callback()
			tx.Error = errors.New(sql.ErrorParams)
			return db, nil
		}

		//
		var bankStatement []model.BankStatement
		if err := tx.Where("bank_statement.function = ? AND bank_statement.function_id = ?", "采购", id).
			Select("bank_statement.*,bank_account.bank,bank_account.account_name,bank_account.card_number,bank_flow.date").
			Joins("left join bank_account ON bank_statement.account_id = bank_account.id").
			Joins("left join bank_flow ON bank_statement.bank_flow_id = bank_flow.id").
			Find(&bankStatement).Error; err != nil {
			tx.Callback()
			tx.Error = errors.New(sql.ErrorParams)
			return db, nil
		}

		for _, statement := range bankStatement {
			str := strings.Replace(statement.CardNumber, " ", "", -1)
			if len(str) > 4 {
				a := []rune(str)
				str = string(a[len(a)-4:])
			}
			bill := model.SettlementBill{
				Model:             gorm.Model{ID: statement.ID},
				PurchaseProductId: statement.FunctionId,
				ContainerNo:       "",
				BankFlowId:        statement.BankFlowId, //银行流水id
				AccountId:         statement.AccountId,  //银行账户id
				Date:              statement.Date,
				Type:              statement.Attribute,
				Amount:            float32(statement.Money),
				Account:           statement.Bank + str,
				IsBankData:        true,
			}
			settlementBill = append(settlementBill, bill)
		}
		return db, settlementBill

	})
}

func settlementBillData(c *gin.Context) {
	sql.HttpDataById(c, &model.SettlementBill{})
}

func settlementBillDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.SettlementBill{})
}
